const express = require('express');
const router = express.Router();
const { DateModel } = require('../databases/model');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 创建新记录
router.post('/date', async (req, res) => {
    try {
        const newDate = new DateModel(req.body);
        await newDate.save();
        res.json({
            code: 200,
            msg: '添加成功',
            data: newDate
        });
    } catch (error) {
        res.status(400).json({
            code: 400,
            msg: '添加失败',
            error: error.message
        });
    }
});

// 获取所有记录
router.get('/date', async (req, res) => {
    try {
        const dates = await DateModel.find();
        res.json({
            code: 200,
            msg: '查询成功',
            data: dates
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '查询失败',
            error: error.message
        });
    }
});

// 获取单个记录
router.get('/date/:id', async (req, res) => {
    try {
        const date = await DateModel.findById(req.params.id);
        if (!date) {
            return res.status(404).json({
                code: 404,
                msg: '未找到该记录'
            });
        }
        res.json({
            code: 200,
            msg: '查询成功',
            data: date
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '查询失败',
            error: error.message
        });
    }
});

// 更新记录
router.put('/date/:id', async (req, res) => {
    try {
        const date = await DateModel.findByIdAndUpdate(
            req.params.id,
            req.body,
            { new: true }
        );
        if (!date) {
            return res.status(404).json({
                code: 404,
                msg: '未找到该记录'
            });
        }
        res.json({
            code: 200,
            msg: '更新成功',
            data: date
        });
    } catch (error) {
        res.status(400).json({
            code: 400,
            msg: '更新失败',
            error: error.message
        });
    }
});

// 删除记录
router.delete('/date/:id', async (req, res) => {
    try {
        const date = await DateModel.findByIdAndDelete(req.params.id);
        if (!date) {
            return res.status(404).json({
                code: 404,
                msg: '未找到该记录'
            });
        }
        res.json({
            code: 200,
            msg: '删除成功',
            data: date
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '删除失败',
            error: error.message
        });
    }
});

module.exports = router;